import React from 'react';
import { cloudServerApiCfg } from '@/api/cloudServerApi'
import { Radio, Slider, Row, Col, InputNumber, Icon, Select, Input, Button } from 'antd';
import { getData } from "@/api/commonApi";
const { Option } = Select;
class CsCom extends React.Component<any, any>{
    constructor(props: any) {
        super(props);
        this.state = {
            // 云服务器数据
            csData: [],
            // 当前选择的云服务器机房
            currentCs: [],
            // 当前选择的云服务器的配置
            currentPzInfo: {
                ipType: "",
            },
            // 当前需要购买的配置
            currentPz: {},
            // 配置清单
            configurationList: cloudServerApiCfg().configurationList,
            // 操作系统
            system: cloudServerApiCfg().system,
            systemS1: "",
            systemS2: [],
            // 验证云主机名称
            validateToCsName: {
                isOk: null,
                msg: "必须以字母开头的4-16位字母+数字"
            },
            // 验证密码
            validateToPwd: {
                isOk: null,
                msg: "操作系统初始密码，必须大于6位"
            },
            // 购买时常数据
            purchaseCycle: [],
            // 基础价格
            baseCost: 0,
        }
    }
    componentDidMount() {
        // console.log(this.props.match.params.code);
        // 初始化
        let systemS1 = this.state.system.s1[0];
        let systemS2 = this.state.system.s2[systemS1];
        this.setState({
            systemS2: systemS2,
            systemS1: systemS1
        })
        this.getCloudServerData();
    }
    render() {
        return (
            <div>
                <div className="c-c-l h100">
                    <div className="c-c-l-tab mb-10">
                        <ul>{this.state.csData.map((item: any, i: number) => {
                            return (
                                <li key={i} className={`${item.active ? 'active' : ""}`} onClick={this.tabChange.bind(this, item)}>{item.title}</li>
                            )
                        })}
                        </ul>
                    </div>
                    <div className="c-c-l-content">
                        <div className="c-c-l-sub-cs mb-10">
                            <Radio.Group options={this.state.currentCs} onChange={this.csChange.bind(this)} value={this.state.currentPz.serverRoom} />
                        </div>
                        <div className="c-c-l-pz">
                            <Row className="mb-10">
                                <Col span={24}>
                                    <Icon type="info-circle" className="mr-10" style={{ color: "red" }} />
                                    声明：谢绝博彩、色情、成人用品以及其他一切非法用途的申请,一经发现,立即关闭,概不退款。
                                    </Col>
                            </Row>
                            <Row className="pz-row mb-10">
                                <Col span={3} className="pz-label">
                                    <span>CPU：</span>
                                </Col>
                                <Col span={15}>
                                    <Slider
                                        min={this.state.currentPzInfo.minCpu}
                                        max={this.state.currentPzInfo.maxCpu}
                                        step={this.state.currentPzInfo.stepCpu}
                                        onChange={this.sliderOnChange.bind(this, 'cpu')}
                                        value={typeof this.state.currentPz.cpu === 'number' ? this.state.currentPz.cpu : this.state.currentPzInfo.minCpu}
                                    />
                                </Col>
                                <Col span={6} style={{ paddingLeft: 10 }}>
                                    <InputNumber
                                        min={this.state.currentPzInfo.minCpu}
                                        max={this.state.currentPzInfo.maxCpu}
                                        style={{ width: 70 }}
                                        value={this.state.currentPz.cpu}
                                        step={this.state.currentPzInfo.stepCpu}
                                        onChange={this.sliderOnChange.bind(this, "cpu")} />
                                    &nbsp;&nbsp;核
                                    </Col>
                            </Row>
                            <Row className="pz-row">
                                <Col span={3} className="pz-label">
                                    <span>内存：</span>
                                </Col>
                                <Col span={15}>
                                    <Slider
                                        min={this.state.currentPzInfo.minRam}
                                        max={this.state.currentPzInfo.maxRam}
                                        step={this.state.currentPzInfo.stepRam}
                                        onChange={this.sliderOnChange.bind(this, 'ram')}
                                        value={typeof this.state.currentPz.ram === 'number' ? this.state.currentPz.ram : this.state.currentPzInfo.minRam}
                                    />
                                </Col>
                                <Col span={6} style={{ paddingLeft: 10 }}>
                                    <InputNumber
                                        min={this.state.currentPzInfo.minRam}
                                        max={this.state.currentPzInfo.maxRam}
                                        style={{ width: 70 }}
                                        step={this.state.currentPzInfo.stepRam}
                                        value={this.state.currentPz.ram}
                                        onChange={this.sliderOnChange.bind(this, "ram")} />
                                    &nbsp;&nbsp;G
                                    </Col>
                            </Row>
                            <Row className="mb-10">
                                <Col span={21} offset={3}>
                                    <Icon type="info-circle" className="mr-10" style={{ color: "#5890ef" }} />
                                    <span style={{ color: "#999", fontSize: 12 }}>为了保证良好的性能体验，512MB内存不建议使用windows操作系统</span>
                                </Col>
                            </Row>
                            <Row className="mb-10">
                                <Col span={3}>
                                    系统盘：
                                    </Col>
                                <Col span={21}>
                                    免费赠送<span style={{ color: 'red' }}>50</span>G系统盘
                                    </Col>
                            </Row>
                            <Row className="pz-row">
                                <Col span={3} className="pz-label">
                                    <span>数据盘：</span>
                                </Col>
                                <Col span={15}>
                                    <Slider
                                        min={this.state.currentPzInfo.minDataDisk}
                                        max={this.state.currentPzInfo.maxDataDisk}
                                        step={this.state.currentPzInfo.stepDataDisk}
                                        onChange={this.sliderOnChange.bind(this, 'dataDisk')}
                                        value={typeof this.state.currentPz.dataDisk === 'number' ? this.state.currentPz.dataDisk : this.state.currentPzInfo.minDataDisk}
                                    />
                                </Col>
                                <Col span={6} style={{ paddingLeft: 10 }}>
                                    <InputNumber
                                        min={this.state.currentPzInfo.minDataDisk}
                                        max={this.state.currentPzInfo.maxDataDisk}
                                        style={{ width: 70 }}
                                        value={this.state.currentPz.dataDisk}
                                        onChange={this.sliderOnChange.bind(this, "dataDisk")} />
                                    &nbsp;&nbsp;G
                                    </Col>
                            </Row>
                            <Row className="mb-10">
                                <Col span={21} offset={3}>
                                    <Icon type="info-circle" className="mr-10" style={{ color: "#5890ef" }} />
                                    <span style={{ color: "#999", fontSize: 12 }}>免费赠送30G，可根据需求增加容量，以10G为步长增加</span>
                                </Col>
                            </Row>
                            <Row className="pz-row">
                                <Col span={3} className="pz-label">
                                    <span>宽带：</span>
                                </Col>
                                <Col span={15}>
                                    <Slider
                                        min={this.state.currentPzInfo.minBroadband}
                                        max={this.state.currentPzInfo.maxBroadband}
                                        step={this.state.currentPzInfo.stepBroadband}
                                        onChange={this.sliderOnChange.bind(this, 'broadband')}
                                        value={typeof this.state.currentPz.broadband === 'number' ? this.state.currentPz.broadband : this.state.currentPzInfo.minBroadband}
                                    />
                                </Col>
                                <Col span={6} style={{ paddingLeft: 10 }}>
                                    <InputNumber
                                        min={this.state.currentPzInfo.minBroadband}
                                        max={this.state.currentPzInfo.maxBroadband}
                                        style={{ width: 70 }}
                                        step={this.state.currentPzInfo.stepBroadband}
                                        value={this.state.currentPz.broadband}
                                        onChange={this.sliderOnChange.bind(this, "broadband")} />
                                    &nbsp;&nbsp;M
                                    </Col>
                            </Row>
                            <Row className="mb-10">
                                <Col span={21} offset={3}>
                                    <Icon type="info-circle" className="mr-10" style={{ color: "#5890ef" }} />
                                    <span style={{ color: "#999", fontSize: 12 }}>以1Mbps为步长增加</span>
                                </Col>
                            </Row>
                            <Row className="mb-10">
                                <Col span={3}>
                                    IP类型：
                                    </Col>
                                <Col span={21}>
                                    <Radio.Group name="ipType" defaultValue={this.state.currentPz.ipType}>
                                        {this.state.currentPzInfo.ipType.split(',').map((item: any, i: number) => {
                                            return (
                                                <Radio value={item} key={i}>{item}</Radio>
                                            )
                                        })}
                                    </Radio.Group>
                                </Col>
                            </Row>
                            <Row className="mb-10">
                                <Col span={3}>
                                    操作系统：
                                    </Col>
                                <Col span={21}>
                                    <Select
                                        defaultValue={this.state.system.s1[0]}
                                        style={{ width: 154.8 }}
                                        onChange={this.systemOnChange.bind(this, 's1')}
                                    >
                                        {this.state.system.s1.map((s1: any) => (
                                            <Option key={s1}>{s1}</Option>
                                        ))}
                                    </Select>
                                    &nbsp;&nbsp;&nbsp;&nbsp;
                                        <Select
                                        style={{ width: 288 }}
                                        value={this.state.currentPz.system}
                                        onChange={this.systemOnChange.bind(this, 's2')}
                                    >
                                        {this.state.systemS2.map((s2: any) => (
                                            <Option key={s2}>{s2}</Option>
                                        ))}
                                    </Select>
                                </Col>
                            </Row>
                            <Row className="pz-row mb-10">
                                <Col span={3}>
                                    云主机名称：
                                    </Col>
                                <Col span={5}>
                                    <Input maxLength={14}
                                        placeholder="输入您的主机名称"
                                        onFocus={this.validateToInput.bind(this, 'validateToCsName', 'focus')}
                                        onBlur={this.validateToInput.bind(this, 'validateToCsName', 'blur')}
                                    />
                                </Col>
                                <Col span={16} style={{ paddingLeft: 15 }}>
                                    {this.state.validateToCsName.isOk === null ?
                                        "" : this.state.validateToCsName.isOk ?
                                            <Icon type="check" style={{ color: "green" }} /> :
                                            <Icon type="close" style={{ color: "red" }} />
                                    }{this.state.validateToCsName.msg}
                                </Col>
                            </Row>
                            <Row className="pz-row mb-10">
                                <Col span={3}>
                                    初始密码：
                                    </Col>
                                <Col span={5}>
                                    <Input.Password maxLength={14}
                                        placeholder="输入初始密码"
                                        onFocus={this.validateToInput.bind(this, 'validateToPwd', 'focus')}
                                        onBlur={this.validateToInput.bind(this, 'validateToPwd', 'blur')}
                                    />
                                </Col>
                                <Col span={16} style={{ paddingLeft: 15 }}>
                                    {this.state.validateToPwd.isOk === null ?
                                        "" : this.state.validateToPwd.isOk ?
                                            <Icon type="check" style={{ color: "green" }} /> :
                                            <Icon type="close" style={{ color: "red" }} />
                                    }{this.state.validateToPwd.msg}
                                </Col>
                            </Row>
                            <Row className="pz-row mb-10">
                                <Col span={3}>
                                    购买时长：
                                    </Col>
                                <Col span={21}>
                                    <Select value={this.state.currentPz.purchaseCycle}
                                        style={{ width: 154.8 }}
                                        onChange={this.purchaseCycleChange.bind(this)}>
                                        {this.state.purchaseCycle.map((item: any) => {
                                            return (
                                                <Option key={item} value={item}>{item}</Option>
                                            )
                                        })}
                                    </Select>

                                </Col>
                            </Row>
                        </div>
                    </div>
                </div>
                <div className="c-c-r h100">
                    <div className="c-c-r-t mb-10">
                        云主机配置信息详单
                        </div>
                    <div className="c-c-r-body">
                        {this.state.configurationList.map((item: any, i: number) => {
                            return (
                                <div className="list-d" key={i}>
                                    <div className="l-d-l">
                                        {item.name}：
                                        </div>
                                    <div className="l-d-r">
                                        {this.state.currentPz[item.code]}
                                        {item.alias ? " " + item.alias : ""}
                                    </div>
                                </div>
                            )
                        })}
                        <Button block type="primary" onClick={this.buySubmit.bind(this)}>购买当前配置</Button>
                    </div>
                </div>
            </div>
        )
    }

    // tab切换
    tabChange(item: any) {
        let tempData = [...this.state.csData];
        this.renderData(tempData, item.title);
    }
    // 服务器机房切换
    csChange(item: any) {
        let currentPz = {};
        let currentCs = [...this.state.currentCs];
        currentCs.forEach((el: any) => {
            if (el.value === item.target.value) {
                currentPz = el.pz;
            }
        })
        this.initCurrentPz(currentPz, item.target.value);
    }

    // slider滑动
    sliderOnChange(item: any, v: any) {
        let currentPz = { ...this.state.currentPz };
        if (item === 'ram') {
            let tempV = Math.round(v * 10) / 10;
            // 是整数
            if (Math.floor(tempV) === tempV) {
                currentPz[item] = tempV;
            } else {
                let num: any = tempV.toString().split('.')[0];
                let num1: any = tempV.toString().split('.')[1];
                let num2: any = num1 * 1 <= 5 ? 0.5 : 1;
                let newV: any = num * 1 + num2;
                currentPz[item] = newV;
            }
        } else {
            currentPz[item] = v;
        }
        // 计算价格
        this.totalPrice(currentPz, this.state.baseCost * 1);
    }
    // 购买时长切换
    purchaseCycleChange(v: any) {
        let currentPz = { ...this.state.currentPz };
        currentPz.purchaseCycle = v;
        let { purchaseCycle, purchasePrice } = this.state.currentPzInfo;
        let baseCost = purchasePrice.split(',')[purchaseCycle.split(',').indexOf(v)];
        // 计算价格
        this.totalPrice(currentPz, baseCost * 1);
    }

    // 计算价格
    totalPrice(currentPz: any, baseCost: number) {
        let { cpuCost, ramCost, broadbandCost, dataDiskCost } = this.computeSum(currentPz);
        currentPz.cost = baseCost + cpuCost + ramCost + dataDiskCost + broadbandCost;
        this.setState({
            baseCost,
            currentPz: Object.assign({}, this.state.currentPz, currentPz),
        });

    }
    // 计算价格Fn
    computeSum(currentPz: any) {
        let currentPzInfo = { ...this.state.currentPzInfo };
        let { cpu, ram, broadband, dataDisk } = currentPz;
        let { cpuPrice, ramPrice, broadbandPrice, dataDiskPrice } = currentPzInfo;
        let pzPrice: any = {
            cpu: cpuPrice.split(','),
            ram: ramPrice.split(','),
            broadband: broadbandPrice.split(','),
            dataDisk: dataDiskPrice.split(','),
        };
        // let dataDiskCost = (dataDisk - currentPzInfo.minDataDisk) * pzPrice.dataDisk[0];
        return {
            cpuCost: this.computeSumFn(currentPzInfo, pzPrice, 'cpu', cpu),
            ramCost: this.computeSumFn(currentPzInfo, pzPrice, 'ram', ram),
            dataDiskCost: this.computeSumFn(currentPzInfo, pzPrice, 'dataDisk', dataDisk),
            broadbandCost: this.computeSumFn(currentPzInfo, pzPrice, 'broadband', broadband),
        }
    }
    // 计算价格Fn2
    computeSumFn(currentPzInfo: any, pzPrice: any, target: any, num: number) {
        let cost = 0;
        let keyName = target.slice(0, 1).toUpperCase() + target.slice(1);
        let step = pzPrice[target][0].split('-')[1];
        if (!step) {
            // console.log(`不存在`, pzPrice[target][0].split('-')[0]);
            cost = (num - currentPzInfo[`min${keyName}`]) * pzPrice[target][0].split('-')[0];
            // (dataDisk - currentPzInfo.minDataDisk) * pzPrice.dataDisk[0];
        } else {
            step = step * 1;
            let step1 = pzPrice[target][1] / currentPzInfo[`step${keyName}`];
            if (num < step + currentPzInfo.stepRam) {
                cost = (num - currentPzInfo[`min${keyName}`]) * step1;
            } else {
                cost = (step - currentPzInfo[`min${keyName}`]) * step1 + (num - step) * (pzPrice[target][2] / currentPzInfo[`step${keyName}`]);
            }
        }
        return cost;
    }


    // 系统切换
    systemOnChange(system: any, v: any) {
        let systemS1 = system === "s1" ? v : this.state.systemS1;
        let systemS2 = this.state.system.s2[systemS1];
        let data: any = {};
        data.system = system === "s2" ? v : systemS2[0];
        this.setState({
            systemS1: systemS1,
            systemS2: systemS2,
            currentPz: Object.assign({}, this.state.currentPz, data),
        })
    }

    // 输入验证
    validateToInput(target: string, event: string, e: any) {
        let data = { ...this.state[target] };
        if (event === "focus") {
            data.isOk = null;
            data.msg = target === "validateToCsName" ? "必须以字母开头的4-16位字母+数字" : "操作系统初始密码，必须大于6位";
            this.validateToInputFn(target, data);
        } else {
            let value = e.target.value;
            if (target === "validateToCsName") {
                let reg1 = new RegExp("^[a-zA-Z]");
                if (!reg1.test(value)) {
                    data.isOk = false;
                    data.msg = "必须以字母开头";
                    this.validateToInputFn(target, data);
                    return
                }
                if (value.length < 3) {
                    data.isOk = false;
                    data.msg = "长度需在4-14位之间";
                    this.validateToInputFn(target, data);
                    return
                }
                let reg2 = new RegExp("^[A-Za-z0-9]+$");
                if (!reg2.test(value)) {
                    data.isOk = false;
                    data.msg = "云主机名称只能字母和数字";
                    this.validateToInputFn(target, data);
                    return
                }
                data.isOk = true;
                data.msg = "验证通过";
                let tempPz: any = {};
                tempPz.csName = value;
                this.setState({ currentPz: Object.assign({}, this.state.currentPz, tempPz) });
                this.validateToInputFn(target, data);
            } else {
                if (value.length < 5) {
                    data.isOk = false;
                    data.msg = "初始密码需在6-14位之间";
                    this.validateToInputFn(target, data);
                    return
                }
                data.isOk = true;
                data.msg = "验证通过";
                let tempPz: any = {};
                tempPz.csPwd = value;
                this.setState({ currentPz: Object.assign({}, this.state.currentPz, tempPz) });
                this.validateToInputFn(target, data);
            }

        }
    }
    // 输入验证赋值Fn
    validateToInputFn(target: string, data: any) {
        let tempObj: any = {};
        tempObj[target] = data;
        this.setState(tempObj);
    }


    // 购买提交
    buySubmit() {
        console.log(`购买提交`, this.state.currentPz);
    }

    // 获取数据
    async getCloudServerData() {
        let res: any = await getData('getCloudServerData');
        if (!res) return;
        // console.log(`请求数据`, res.data);
        this.renderData([...res.data], res.data[0].title);
    }

    // 渲染数据
    renderData(data: any, title: string) {
        // copy数据
        let tempData = [...data];
        // 重新定义当前选择服务器的机房
        let currentCs: any = [];
        tempData.forEach((el: any) => {
            if (el.title === title) {
                el.active = true;
                el.subCs.forEach((el1: any) => {
                    currentCs.push({
                        label: el1.csName,
                        value: el1.csName,
                        pz: el1.pz
                    })
                })
            } else {
                el.active = false;
            }
        })
        // 获取当前云机器的配置信息
        let cuttentPzInfo: any = currentCs[0].pz;
        // 获取当前云机器的购买时长
        let purchaseCycle = cuttentPzInfo.purchaseCycle.split(',');
        // init 当前配置
        this.initCurrentPz(cuttentPzInfo, currentCs[0].label);
        this.setState({
            csData: data,
            currentCs: currentCs,
            purchaseCycle: purchaseCycle,
        })
    }

    // init 当前配置信息
    initCurrentPz(data: any, serverRoom: string) {
        let currentPz = {
            cpu: data.minCpu,
            ram: data.minRam,
            dataDisk: data.minDataDisk,
            broadband: data.minBroadband,
            ipType: data.ipType.split(',')[0],
            serverRoom: serverRoom,
            system: this.state.systemS2[0],
            purchaseCycle: data.purchaseCycle.split(',')[0],
            cost: data.purchasePrice.split(",")[0],
        };
        this.setState({
            baseCost: data.purchasePrice.split(",")[0],
            currentCsValue: serverRoom,
            currentPzInfo: data,
            currentPz: Object.assign({}, this.state.currentPz, currentPz),
        })

    }
}

export default CsCom;
